AI.Meta = Event.$extend({
  _listeners:{},
  objStore: {},///当前对象基本信息的store
  objrecord: {},///当前对象的记录
  xmlid:paramMap.xmlid||"",///当前对象的全局编码
  objname: paramMap.OBJNAME || '',
  objcnname : paramMap.OBJCNNAME || '',
  metaprj : paramMap.METAPRJ || "",
  objtype : paramMap.OBJTYPE || 'TAB',
  opttype : paramMap.OPTTYPE || '',
  teamcode : paramMap.TEAM_CODE || "", 
  actItmes:null,///所有的操作列表
  ActionDef:null, 
  actType: "add",///当前对象是新建，编辑
  rightLevel:'edit',///当前用户对当前对象的编辑权限,readOnly,edit
  isDirty:'',///当前对象是否修改还没保存
  clipboard:null,//剪贴板
  inputCheckReg:null,//输入验证规则{}
  // getClipboard:function(){return this.clipboard},
  // setClipboard:function(){},
  metaModelList:{
    "folder":{ metaInfo:{OBJICON:'glyphicon-folder-open',detailurl:'http://www.baidu.com'}
            ,metaAttr:""
            ,metaAction:""
            ,objproperty:[]
    }
  },/*metaInfo,metaAttr,metaAction*/
  SLAVE_TABS:{
      TAB:["COLUMN_VAL","TABLEINDEX","TABLEPARTITION"],
      PROC:["PROC_STEP"],
      DATABASE:["METADB_STRUCT","METAOBJ_PROPERTY"]
  },
  __init__ : function(options) {
    this.options= $.extend(true, this.default, options);
    //    this.$super(options);
    this._listeners={};
    this.init( this.options);
    this.objtype=options.objtype;
    this.teamcode = options.teamcode||'';
  },
  initInputCheckReg:function(){
    var store = new AI.JsonStore({
      sql : "SELECT rowcode,rowname FROM metaedimdef where dimcode='DIM_INPUTCHECK_REG'"
    });
    this.inputCheckReg = {};
    for(var i = 0 ,len = store.getCount(); i < len ; i++ ){
      var record = store.getAt(i);
      this.inputCheckReg[record.get("ROWCODE")] = record.get("ROWNAME");
    }
  },
  destroy:function(){
  //  this.delete();
  },
  reload:function(){},
  init:function(options){
    this.objtype=options.objtype;
    this._METAPRJ=paramMap.METAPRJ?'_'+paramMap.METAPRJ:'';
  },
  getMetaModel: function(objtype) { ////取元模型信息，metaInfo,attrArray,actionItems
    ///相关表:METAOBJINFO:基本信息配置表,属性配置表:METAOBJCFG,
    function getTypeActItems(objType, parentcode) {     
      var items = [];
      if(!objType) return items;
      var itemStore=ai.getStoreData("SELECT actcode,actname,parentcode,provider,url,actfun,refmodel,getright,iconclass,dockplace FROM metasoft_action WHERE (refmodel LIKE '%"+objtype+"%' OR refmodel = '*') ORDER BY ordseq ");
      items=getTypeActData(objType,parentcode,itemStore);
      
      return items;
    }
    
    function getTypeActData(objType, parentcode,itemStore){
      var items=[];
      if(!parentcode) {
      if(itemStore.length>0){
        for(var i=0;i<itemStore.length;i++){
            if(!itemStore[i].PARENTCODE){
            items.push(itemStore[i]);
            }
          }
      }
        }else {          
         if(itemStore.length>0){
          for(var j=0;j<itemStore.length;j++){
            if(itemStore[j].PARENTCODE==parentcode){
            items.push(itemStore[j]);
            }
          }
         }
        }
        
        for(var k=0; k<items.length; k++) {
          var subItems = getTypeActData(objType, items[k].ACTCODE,itemStore);
            if(subItems.length != 0) {
              items[k].items = subItems;
            } 
        }
        
        return items;
    }

    if(!objtype) return;
    if(!this.metaModelList[objtype]){
      var sendObj = {
          paras: [{
              paraname: "objinfo",
              paratype: "map",
              sql: "select OBJTYPE, OBJCODE, OBJNAME, ORDSEQ, REMARK, TABNAME,  RULETAB, KEYFIELD, NAMEFIELD, LOGTAB, TIMEFIELD, RUNTABNAME,  DETAILURL, RUNURL,OBJACT,OBJICON,CHGURL,PARENTCODE from metaobjmodel where objtype='" + objtype + "'"
          }, {
              paraname: "objattr",
              paratype: "array",
              sql: "select OBJTYPE, ATTRGROUP, ATTRNAME, ATTRCNNAME, INPUTTYPE,INPUTPARA, ISNULL, SELVAL, SELMODEL, SEQ, REMARK, DEPENDENCIES, CHECKITEMS, MINLENGTH,MAXLENGTH,ATTRROW from METAOBJCFG"+(this._METAPRJ||'')+" where objtype='" + objtype+ "' order by ATTRGROUP,SEQ "
          }, {
              paraname: "objproperty",
              paratype: "array",
              sql: "SELECT PARACODE,PARATEXT  FROM metaobjmodel_def where objtype='" + objtype+ "'"
          }]
      };
      var URL = '/' + contextUrl + '/olapquery?json=' + ai.URLEncode(ai.encode(sendObj));
      var obj = ai.remoteData(URL);
      var metaModel={metaInfo:'',attrArray:'',actionItems:[]};
      if(obj.root &&obj.root.length)  metaModel = {metaInfo:obj.root[0].objinfo,attrArray:obj.root[1].objattr,actionItems:{},objproperty:obj.root[2].objproperty};

      ///加载所有的操作列表
      // if(!this.actItmes)  this.actItmes=ai.getStoreData("select rowcode,rowname,type,remark from metaedimdef WHERE dimcode='DIM_ACTION'");
      if(!this.actItmes){
        this.actItmes = {};
        this.actItmes[objtype]=getTypeActItems(objtype);
      }
      else if(!this.actItmes[objtype]){
        this.actItmes[objtype]=getTypeActItems(objtype);
      }

      var getItemJSON = function(item) {
        var createGetRight = function(item) {
          var getRight = function(){console.log("hello getRight!")};
          if(item.GETRIGHT){
            eval("getRight = "+item.GETRIGHT);
          } 
          return getRight;
        }
        item.ICONCLASS = " " + item.ICONCLASS;
        if(item.items) {
          var json = {};
          for(var i=0; i<item.items.length; i++) {
            var subItem = item.items[i];
            eval("json." + subItem.ACTCODE + " = getItemJSON(subItem)");
          }
          // console.log(json);
          var resultJson = {name:item.ACTNAME,icon:item.ICONCLASS||"info",accesskey:'i',url:item.URL,actfun:item.ACTFUN,getright:createGetRight(item),dockplace:item.DOCKPLACE};
          resultJson.items = json;
          // console.log(resultJson);
          return resultJson;
        }
        return {name:item.ACTNAME,icon:item.ICONCLASS||"info",accesskey:'i',url:item.URL,actfun:item.ACTFUN,getright:createGetRight(item),dockplace:item.DOCKPLACE};
      }

      if(!metaModel.actionItems[objtype]){
        metaModel.actionItems[objtype] = {}
        for(var i=0;i<this.actItmes[objtype].length;i++){
          var item=this.actItmes[objtype][i];
          metaModel.actionItems[objtype][item.ACTCODE]= getItemJSON(item);
        }
      }
      this.metaModelList[objtype]=metaModel;
    };
    return this.metaModelList[objtype];
  },
  getMetaInfo:function(objtype){///取元模型基本信息
    var metaModel = this.getMetaModel(objtype);
    if(!metaModel) return;
    var keyfield = metaModel.metaInfo.keyfield;
    if(keyfield) {
    	var keyfields = keyfield.split(',');
    	metaModel.metaInfo.multiKeyField = keyfield;
    	metaModel.metaInfo.keyfield = keyfields[0];
    }
    return metaModel.metaInfo;
  },
  getMetaAttr:function(objtype){///取元模型基本信息
    var metaModel = this.getMetaModel(objtype);
    if(!metaModel) return;
      return metaModel.attrArray;
  },
  getMetaProPerty:function(objtype,pro_key){///取元模型扩展信息
    var metaModel = this.getMetaModel(objtype);
    if(!metaModel) return;
    var result;
    var properties = metaModel.objproperty;
    if(!properties) return "";
    for(var i=0;i<properties.length;i++){
    if(properties[i].paracode==pro_key){
       result = properties[i].paratext;
       break;
      };
    };
    return result;
  },
  getMetaObjProperty:function(xmlid,pro_key){///对象的扩展信息
    if(!xmlid) return;
    var result ="";
    var data = ai.getStoreData("select pro_value from metaobj_property where xmlid='"+xmlid+"' and pro_key='"+pro_key+"'");
    if(data.length>0) result=data[0].PRO_VALUE;
    return result;
  },
  getMetaColumn:function(objtype){

  },
  getMetaObjActionItems:function(objtype,dockplace){///获取每个对象的菜单项
    dockplace = dockplace||'all';
    var metaModel = this.getMetaModel(objtype);
    if(!metaModel||!metaModel.actionItems) return;
    if(dockplace == 'all') return metaModel.actionItems[objtype];
    var actionIds = _.keys(metaModel.actionItems[objtype]);
    var actionItems = {};
    for(var i=0;i<actionIds.length;i++){
      var actionId = actionIds[i];
      var dockplaces = metaModel.actionItems[objtype][actionId].dockplace||"";
      dockplaces = dockplaces.split(',');
      if(_.indexOf(dockplaces,dockplace) != -1){
        actionItems[actionId] = metaModel.actionItems[objtype][actionId];
      }
    }
    return actionItems;  
  },
  getMetaObjIcon:function(objtype){
    if(objtype=="folder") return " glyphicon-folder-close "
    var metaInfo =this.getMetaInfo(objtype);
    if(!metaInfo) return 'glyphicon-plus';
    return metaInfo.objicon||'glyphicon-plus'
  },
  getNewObjRecord:function(){  ///当对象不存在时，新建一个对象的操作
    this.objrecord=this.objStore.getNewRecord();
    for (var key in paramMap) {
      this.objrecord.set(key.toUpperCase(), paramMap[key]);
    };
    this.objrecord.set('XMLID', ai.guid());
    this.xmlid = this.objrecord.get('XMLID');
    //OBJNAME = this.objrecord.get('XMLID');
    this.objrecord.set('TEAM_CODE', paramMap['TEAM_CODE']);
    this.objrecord.set('CREATER', _UserInfo['username']);
    this.objrecord.set('EFF_DATE', new Date());
    this.objrecord.set('STATE', '新建');
    this.objrecord.set('STATE_DATE', new Date());
    this.objrecord.set('CURDUTYER', _UserInfo['username']);
    this.objrecord.set('VERSEQ', 1);
    this.objrecord.set('OBJTYPE', this.OBJTYPE);
    this.objrecord.set(this.metaInfo.nameField, this.OBJCNNAME);
    this.objStore.add(this.objrecord);
  },
  getRightLevel:function(){////根据当前用户信息和内容信息，判断用户是否有权限编辑
    return "edit";
    ///如果当前负责人是当前用户&当前状态不为发布，则可以编辑
  },
  getPickSelectSql:function(attrName,storesql){////根据当前用户信息，修改可以选择对象的内容sql语句，外部可以调用
       return storesql;
  },
  getFormItems:function(attrArray,objStore,attrGroup,objType,actType){
    var metaInfo = this.getMetaInfo(objType||this.objtype);
    actType = actType||'add';
    attrGroup = attrGroup||'';
     var formItems = [];
    for (var i = 0; i < attrArray.length; i++) {
      var attrItem = attrArray[i];
      var attrrow = attrItem.attrrow||i;
      if(actType == 'edit'&&attrItem.attrname==metaInfo.keyfield){
        attrItem.readOnly = 'y';
      }
      if (attrGroup.indexOf('基本信息')!=-1&&attrItem.attrgroup.indexOf('基本信息')==-1) continue;
      if (attrGroup.indexOf('基本信息')!=-1&&attrItem.attrgroup.indexOf('基本信息')!=-1) {
        attrrow = i;
      }
      defaultwidth = 320;
      if (attrItem.inputtype == 'check') attrItem.inputtype = 'checkbox';
      if (attrItem.inputtype == 'combo') attrItem.inputtype = 'combox';
      if (attrItem.inputtype == 'label') continue; //attrItem.inputtype='html';
      if (!attrItem.inputtype) attrItem.inputtype = 'text';
      // if (actType == "readOnly") attrItem.readOnly = 'y';
      if (_UserInfo.username == 'sys') attrItem.readOnly = 'n';
      if(attrItem.attrname=='TEAM_CODE'&&objStore.getCount()>1) attrItem.readOnly = 'y';
      if (attrItem.inputpara && attrItem.inputpara.length > 0) {
          attrItem.inputpara = attrItem.inputpara.replace(/{team_code}/g, this.teamcode).replace('{username}', _UserInfo['username']);
      }
       
      var formItem = {
        fieldset:attrItem.attrgroup ||'...',//fieldsets分组标准
        type: attrItem.inputtype || 'text',
        label: attrItem.attrcnname,
        labelColSpan:3,
        notNull: attrItem.isnull || 'Y',
        storesql: attrItem.inputpara,
        isReadOnly: attrItem.readOnly || '',
        fieldName: attrItem.attrname,
        dependencies: attrItem.dependencies,
        checkItems: attrItem.checkitems,
        width: defaultwidth,
        tip: attrItem.remark,
        editable:attrItem.editable||'N'
      }
//      if(formItems[attrrow]) {
//        formItems[attrrow].push(formItem);
//      }
//      else{
//        var colItems = [formItem];
//        formItems[attrrow] = colItems;
//      }
      formItems.push(formItem);
    }
    //return _.values(formItems);
    return formItems;
  },
  getNewMetaObjStore:function(metaInfo,objid){
    var sql="select * from " + metaInfo.tabname ;
    var secondTable="METAOBJ";
    //保存数据库信息时，新增信息保存到表METADB_LIST中
    if(metaInfo.objtype!=null&&metaInfo.objtype=='DATABASE'){
      secondTable="METAOBJ,METADB_LIST"
    }
    if(metaInfo.objtype!=null&&metaInfo.objtype=='TAB'){
      secondTable="METAOBJ,data_storage_rule"///新增信息保存到data_storage_rule20160523
    }
    
    if(objid) sql+=" where  XMLID='"+objid+"'"
    else sql+=" where 1=2  " ;
    var objStore = new AI.JsonStore({
      sql: sql ,
      table: metaInfo.tabname,
      loadDataWhenInit: true,
      secondTable:secondTable,
      key: "XMLID"
    });
    return objStore;
  },
  registNewMetaObj:function(options){////新建元数据对象表单{objtype:,objid,objStore,beforeSave,aftSave,initVals}
    var self = this;
    var objtype=options.objtype;
    var objid = options.objid;
    var objStore =options.objStore;
    var beforeSave=options.beforeSave;
    var aftSave=options.aftSave;
    var initVals=options.initVals;
    var actType = options.actType||'add';
   
    /// objtype,beforeSave,aftSave,initVals
    var metaModel =  this.getMetaModel(objtype);
    var metaInfo = metaModel.metaInfo;
    var attrArray = metaModel.attrArray;
    var objrecord = null;
    ///metaobj.objname->keyfield,cnname->namefield
 
    function chekNameIsUniquoe() {
      var message = '';
      var result =[];
      var keyfields = metaModel.metaInfo.multiKeyField;
      var chkObjname = objrecord.get("OBJNAME");
      var chkObjcnname = objrecord.get("OBJCNNAME");
      message += 'OBJNAME='+chkObjname +'\n';
      var chksql="select objname,team_code from metaobj where objtype='"+objtype+"' and objname='"+chkObjname+"'";
      if(objtype == 'TAB'){
      	var otherWhereClause = '';
      	if(keyfields){
      		keyfields = keyfields.split(',');
      		for(var i=1;i < keyfields.length;i++) {
          		var key = keyfields[i];
          		 message += ''+key+'='+objrecord.get(key) +'\n';
          		otherWhereClause +=" and "+key+"='"+objrecord.get(key)+"' ";
          	}
      	}
      	
        //chksql += " and dbname = '"+objrecord.get('DBNAME')+"' and SCHEMA_NAME = '"+objrecord.get('SCHEMA_NAME')+"' ";
        if(!objrecord.get('DBNAME')) {
          chksql += " and dbname is null ";
        } else {
          chksql += " and dbname = '" + objrecord.get('DBNAME') + "' ";
        } 
      	chksql += otherWhereClause;
        
      }else if(objtype == 'TEAM'){
        chksql += " and team_code = '"+objrecord.get('TEAM_CODE')+"' ";
      }else if(objtype == 'PROC'){
        chksql += " and team_code = '"+objrecord.get('TEAM_CODE')+"' ";
      }else if(objtype =='DATABASE'){
      	chksql = "select objname,team_code from metaobj where objtype='"+objtype+"' and (objname='"+chkObjname+"' OR objcnname='"+chkObjcnname+"')";
      	if(actType=='edit'){
	      	chksql += " and xmlid<>'"+objrecord.get('XMLID')+"'";
      	}
      }
      var tmpStore = new AI.JsonStore({sql:chksql});
      if(actType=='add'&&tmpStore.getCount()>0){
        if(objtype == 'TAB'){
          //alert("已经存在相同的对象:"+message);
        	result.push("已经存在相同的对象:"+message);
        }else if(objtype == 'TEAM'){
          //alert("租户编码重复!");
        	result.push("租户编码重复!");
        }else if(objtype == 'PROC'){
          //alert("程序名重复!");
        	result.push("程序名重复!");
        }else if(objtype == 'DATABASE'){
        	//alert("数据库名称或者中文名重复!");
        	result.push("数据库名称或者中文名重复!");
        }
        //return false;
      }
      if(actType=='edit'&&tmpStore.getCount()>0&&tmpStore.getAt(0).get('OBJNAME')!=chkObjname&&objtype == 'TAB') {
        if(objtype == 'TAB')
          //alert("已经存在相同的对象名称:"+chkObjname);
          //return false;
        	result.push("已经存在相同的对象名称:"+chkObjname);
      } else if(actType=='edit'&&tmpStore.getCount()>0&&tmpStore.getAt(0).get('TEAM_CODE')!=objrecord.get("TEAM_CODE")&&objtype == 'TEAM') {
        //alert("租户编码重复!");
        //return false;
    	  result.push("租户编码重复!");
      }else if(actType=='edit'&&objtype == 'DATABASE'&&tmpStore.getCount()>0){
        //alert("数据库名称或者中文名重复!");
    	  result.push("数据库名称或者中文名重复!");
       // return false;
      }
      
      if(result.length>0){
    	  artDialog.alert(result.join("<br>"));
    	  return false;
      }
      
      return true;
    }
    function getMetaFieldLabel(metaModel,keyfield){
      var attrArray=metaModel.attrArray;
      var label="";
      for (var i = 0; i < attrArray.length; i++) {
        var attr=attrArray[i];
        if(attr.attrname==keyfield){
          label=attr.attrcnname;
          break;
        }
      }
      return label;
    }
    
    function checkInputForm(){
      var result =true;
      var resultMessage =[];
      //校验主表keyfield是否符合规范
      var recKey = objrecord.get(metaModel.metaInfo.keyfield);
      if(self.inputCheckReg == null){
        self.initInputCheckReg();
      }
      var regx = self.inputCheckReg[objtype];
      if(!regx) regx = "^[a-zA-Z][a-zA-Z0-9_]*$";
      regx = new RegExp(regx);
      if((objtype=='TAB'||objtype=='DATAFLOW')&&metaModel.metaInfo.parentcode != "META-OTHER"&&!regx.test(recKey)){
        var label=getMetaFieldLabel(metaModel,metaModel.metaInfo.keyfield);
        //alert("["+label+"]需以字母开头，并且只能包含字母、数字、下划线");
        //return false;
        resultMessage.push("["+label+"]需以字母开头，并且只能包含字母、数字、下划线");
      } else if(objtype == 'PROC') {
        
      }
      //datafield是否符合规范20160523
      if(metaModel.metaInfo.objtype=="TAB") {
        var chk_datafield = objrecord.get('DATEFIELD');
        if (chk_datafield!=undefined) {
          var chk = /^(-1)?[0-9]*$/;
          if(!chk.test(chk_datafield)) {
            //alert("请填写正确的周期值");
            //return false;
        	  resultMessage.push("请填写正确的周期值");
          }
        }
      }
      ///检查是否不允许为空,长度是否在允许范围之类
      var extend_cfg={};
      var extend_cfgstr = objrecord.get('EXTEND_CFG');
      if (extend_cfgstr) {
        extend_cfg = JSON.parse(extend_cfgstr);
      }
      for(var i=0;i<attrArray.length;i++){
        var attr = attrArray[i];
        if(attr.isnull=='N' && attr.attrgroup == '1.基本信息'){
          if(attr.attrname.indexOf("EXTEND_CFG.")>=0){
            var attrKey = attr.attrname.split(".")[1];
            if(!extend_cfg[attrKey]){
              //alert(attr.attrcnname+",扩展信息,不允许为空");
              //result=false;
            	resultMessage.push(attr.attrcnname+",扩展信息,不允许为空");
              //break;
            }
          }else if( !objrecord.get(attr.attrname) ){
             //alert(attr.attrcnname+"不允许为空");
             //result=false;
        	  resultMessage.push(attr.attrcnname+"不允许为空");
             //break;
          }
        }
        if(attr.attrname.indexOf("EXTEND_CFG.")>=0){
          if(objrecord.get(attr.attrname)&&attr.maxlength&&extend_cfg[attrKey].length>attr.maxlength){
            //alert(attr.attrcnname+"长度超出,请控制在"+attr.maxlength+"以内");
            //result=false;
        	  resultMessage.push(attr.attrcnname+"长度超出,请控制在"+attr.maxlength+"以内");
            //break;
          }
        }else if(objrecord.get(attr.attrname)&&attr.maxlength&&objrecord.get(attr.attrname).length>attr.maxlength){
          //alert(attr.attrcnname+"长度超出,请控制在"+attr.maxlength+"以内");
          //result=false;
        	resultMessage.push(attr.attrcnname+"长度超出,请控制在"+attr.maxlength+"以内");
          //break;
        }
      }
      
      if(resultMessage.length>0){
    	  artDialog.alert(resultMessage.join("<br>"));
    	  return false;
      }
      // if(!result) return false;
      // ///检查名称的唯一性
      // result = chekNameIsUniquoe();
      return result;
    }
    function afterOK(fieldval){ 
    	//开发规范检查
    	var ckrs="0";
        var tmp=ai.getJsonStore("select devck from metaobjmodel where objtype='"+objtype+"'");
	        if(tmp.getCount()>0 && (tmp.getAt(0).get("DEVCK")=="y" || tmp.getAt(0).get("DEVCK")=="Y")){
	      	var tmpStore= new AI.JsonStore({
	                sql : "select * from "+metaInfo.tabname +" where 1=2",
	                table:metaInfo.tabname,
	                secondTable:"METAOBJ",
	                pageSize : -1
	              }); 
	      	 var newRecord = objStore.getAt(0);
	      	 if(actType=='add'){
		      	tmpStore.add(newRecord);
		      	tmpStore.commit();
	      	 }
	          var loading='<div id="loading" '
	          +'style="width:250px;'  
	          +'height:56px;  '
	          +'position: absolute; ' 
	          +'top:50%;  '
	          +'left:50%;  '
	          +'line-height:56px; ' 
	          +'color:#fff;  '
	          +'padding-left:60px; ' 
	          +'font-size:15px;  '
	          +'background: #000 url(../../../dacp-res/me/images/loader.gif) no-repeat 10px 50%; ' 
	          +'opacity: 0.7;  '
	          +'z-index:9999; ' 
	          +'-moz-border-radius:20px;  '
	          +'-webkit-border-radius:20px;  '
	          +'border-radius:20px;  '
	          +'filter:progid:DXImageTransform.Microsoft.Alpha(opacity=70); "'
	          +'>开发规范检查中,请等待...</div>';

	          $(loading).appendTo("body");
	          
	          var r=objStore.getAt(0);
	          var xmlid =  !r.get('XMLID')?ai.guid():r.get('XMLID');
	          var RSKEY='';
	          if(objtype=="TAB"){
	            RSKEY='tablefile';
	          }
	          var URL="/"+contextPath+"/me/dq/doCkAsModel?objtype="+objtype+"&cktype=dev&metaid="+xmlid+"&rskey="+RSKEY;
	          var robj=ai.remoteData(URL,false);
	          $("#loading").remove();
	          ckrs=robj.rs;
	          if(ckrs=="-1"){ 
	  	         var srcUrl="/"+contextPath+"/ftl/me/quality_rpt/DqRsDevDetail?XMLID="+robj.xmlid+"&OBJID="+xmlid+"&OBJTYPE="+objtype+"&OBJNAME="+r.get(metaInfo.keyfield)+"&RSKEY="+RSKEY;
	  	         ai.openDialog(srcUrl,xmlid,"检查结果",'','');	         
	  	         //不通过是否删除数据  actType=='add'
	  	         if(actType=='add'){
	  	        	 var rs=ai.executeSQL("delete from "+metaInfo.tabname+" where XMLID='"+xmlid+"' ");
	  	        	 var rs=ai.executeSQL("delete from metaobj where XMLID='"+xmlid+"' ");
	  	         }	         
	  	         return false;
	          }
	          //删除临时提交
	          if(actType=='add'){
		        	 var rs=ai.executeSQL("delete from "+metaInfo.tabname+" where XMLID='"+xmlid+"' ");
		        	 var rs=ai.executeSQL("delete from metaobj where XMLID='"+xmlid+"' ");
		       }	
      }
      if(ckrs=="0"){//正常提交
    	  objStore.commit();  
      }

      if(objStore.curRecord.get('OBJTYPE') == "DATABASE") {  //初始化数据库菜单目录
        var rec = objStore.curRecord;
        var dbxmlid = rec.get('XMLID');
        var dbname = rec.get('OBJNAME');
        var dbtype = rec.get('CYCLETYPE');

        var delsql = "delete from metamodel where modelcode like '"  + dbname + "%'";
        ai.executeSQL(delsql);

        var store = new AI.JsonStore({
          sql : "select * from metamodel",
          table:'metamodel',
          pageSize : -1
        }); 

        var modelStore = new AI.JsonStore({
          sql : "select * from metaobjmodel_def",
          table:'metaobjmodel_def',
          pageSize : -1
        }); 

        var code = dbname;

        for(var i=0; i<modelStore.getCount(); i++) {
          var r = modelStore.getAt(i);
          var type = 'DATABASE-' + dbtype;
          var paracode = r.get('PARACODE');

          var seq = r.get('ORDSEQ');
          var modeltype = r.get('PARATYPE');
          var parentcode = r.get('PARENTCODE');
          var modelcode = r.get('ATTRCODE');
          var modelname = r.get('PARANAME');
          var url = r.get('PARATEXT');
          var remark = r.get('REMARK');

          if(paracode != 'dbmgr' || r.get('OBJTYPE') != type) {
            continue;
          }

          var newRecord = store.getNewRecord();

          newRecord.set('MODELCODE', modelcode.replace("dbmgr", dbname));
          if(parentcode) {
            newRecord.set('PARENTCODE', parentcode.replace("dbmgr", dbname));
          }
          newRecord.set('MODELNAME', modelname);
          newRecord.set('MODELTYPE', modeltype);
          newRecord.set('REMARK', remark);
          newRecord.set('CLASSTYPE', 'TFMoniteShow');
          newRecord.set('SEQ', seq);
          newRecord.set('IMAGEINDEX', 1);
          newRecord.set('FRAME', 'content');
          if(url) {
            newRecord.set('URL', url.replaceAll("{DBXMLID}", dbxmlid));
          }
          newRecord.set('IMAGES', 'fa fa-list-alt');
          newRecord.set('STATE', 'on');

          if(modelname == '数据库管理') {
            newRecord.set('MODELNAME', '数据库管理-' + dbname);
          }

          var pModelcode = "'" + newRecord.get("MODELCODE") + "'";
          var pParentcode = "'" + newRecord.get("PARENTCODE") + "'";
          var pModelname = "'" + newRecord.get("MODELNAME") + "'";
          var groupcode = "'SysMgr'";
          var permissionlevel = "'2'";

          ai.executeSQL("delete from metapermission where modelcode = '" + newRecord.get("MODELCODE") + "' and groupcode = 'SysMgr'");

          if(!newRecord.get("PARENTCODE")) {
            pParentcode = "null";
          }
          var insertSql = "insert into metapermission values(" + pModelcode + ", " + groupcode + ", " + pModelname + ", " + pParentcode + ", " + permissionlevel + ")";

          store.add(newRecord);
          ai.executeSQL(insertSql);
        }
        store.commit();
      }

      if(objStore.curRecord.get('OBJTYPE') == "TEAM") {   //将团队管理员记录添加到meta_team_role_user表
        var xmlid = objStore.curRecord.get('XMLID');
        var teamcode = objStore.curRecord.get('OBJNAME');
        var rec = ai.getStoreData("select TEAM_MGR from meta_team where xmlid = '" + xmlid + "'");
        if(rec.length == 0) {
          return;
        }
        var mgrs = rec[0].TEAM_MGR || "";
        var mgrArr = mgrs.split(",");
        if(mgrArr.length == 0) {
          return;
        }
        ai.executeSQL("delete from meta_team_role_user where team_code = '" + teamcode + "' and role_code = 'teamMgr'");

        var userStore = new AI.JsonStore({
          sql: "select username, usecnname from metauser",
          table: "METAUSER",
          key: "USERNAME",
          pageSize: -1
        });

        var roleUserStore = new AI.JsonStore({
          sql: "select * from meta_team_role_user",
          table: "META_TEAM_ROLE_USER"
        });

        for(var i in mgrArr) {
          var username = mgrArr[i];
          if(!username) {
            break;
          }
          var usercnname = userStore.getRecordByKey(username).get("USECNNAME");
          var r = roleUserStore.getNewRecord();
          r.set("TEAM_CODE", teamcode);
          r.set("ROLE_CODE", "teamMgr");
          r.set("USERNAME", username);
          r.set("REMARK", usercnname);
          roleUserStore.add(r);
          roleUserStore.commit();
        }
      }

      ///对data_storage_rule表进行个性化更新；周期类型是分钟或小时时，以day保存；20160523
      if(objStore.getAt(0).get('OBJTYPE')=="TAB"){
        var cycletype = objStore.getAt(0).get('CYCLETYPE');
        if(cycletype=="minute"||cycletype=="hour"){
          cycletype = "day";
        }
        //增加更新判断20160531
        var updcount = new AI.JsonStore({sql:"select DATANAME from data_storage_rule where DBNAME = '"+objStore.getAt(0).get('DBNAME')+"' AND DATANAME = '"+objStore.getAt(0).get('DATANAME')+"'"});
        if(updcount.getCount()>0){
          var upd_data_storage_rule = ai.executeSQL("update data_storage_rule set CYCLETYPE = '"+cycletype+"', DURATION = '"+objStore.getAt(0).get('DATEFIELD')+"',STATE = 'on',STATE_DATE = to_date('"+objStore.getAt(0).get('STATE_DATE')+"','yyyy-mm-dd hh24:mi:ss'),IS_WHITE = 'N' where DBNAME = '"+objStore.getAt(0).get('DBNAME')+"' AND DATANAME = '"+objStore.getAt(0).get('DATANAME')+"'");
        }else{
          var editdate = new Date().format("yyyy-mm-dd hh:mm:ss").toLocaleString().toString(); 
          var add_data_storage_rule = ai.executeSQL("insert into data_storage_rule (DBNAME,DATANAME,CYCLETYPE,DURATION,CURDUTYER,EFF_DATE,STATE,STATE_DATE,IS_WHITE) values ('"+objStore.getAt(0).get('DBNAME')+"', '"+objStore.getAt(0).get('DATANAME')+"', '"+cycletype+"', '"+objStore.getAt(0).get('DATEFIELD')+"', '"+objStore.getAt(0).get('CURDUTYER')+"', to_date('"+objStore.getAt(0).get('EFF_DATE')+"','yyyy-mm-dd hh24:mi:ss'), 'on', to_date('"+editdate+"','yyyy-mm-dd hh24:mi:ss'), 'N')");
        }
      }

      self.reload();
      if(aftSave) return aftSave(fieldval,objStore,objStore.curRecord);
    };
    function beforeOK(fieldval){//进行检验
      if(!checkInputForm()) return false;
        var r=objStore.getAt(0);
        var xmlid =  !r.get('XMLID')?ai.guid():r.get('XMLID');
        r.set('XMLID', xmlid);
        r.set('OBJTYPE', objtype);
        r.set('OBJNAME',r.get(metaInfo.keyfield));
        r.set('OBJCNNAME',r.get(metaInfo.namefield));
        if(!r.get('TEAM_CODE')) r.set('TEAM_CODE',self.teamcode||'');
        if(r.get('PASSWORD')){
          if(actType=="edit"){
            var recPreData = ai.getJsonStore(" select * from "+metaInfo.tabname+" where XMLID='"+xmlid+"' ");
            if(recPreData.getAt(0).get("PASSWORD") != r.get('PASSWORD')){
              var URL="/"+contextPath+"/crypto/encrypt/des?message="+encodeURIComponent(r.get("PASSWORD"));
              var obj=ai.remoteData(URL);
                  r.set('PASSWORD',obj);
            }
          }else if(actType=="add"){
            var URL="/"+contextPath+"/crypto/encrypt/des?message="+encodeURIComponent(r.get("PASSWORD"));
          var obj=ai.remoteData(URL);
              r.set('PASSWORD',obj);
          }
        }
      //TODO隐形命名规范
      if(objtype=='TAB'){
        r.set('OBJNAME',r.get('OBJNAME').toUpperCase());
        r.set('DATANAME',r.get('DATANAME').toUpperCase());
      }
      if(objtype=='PROC'){
        r.set('OBJNAME',r.get('OBJNAME').toLowerCase());
        r.set('PROC_NAME',r.get('PROC_NAME').toLowerCase());
      }
      //end
          
      if(beforeSave) beforeSave(fieldval,objStore,r);
      if(objtype=='PROC'){
       // if($("#_global_from #PROCTYPE").length == 0) {
        if(!fieldval.PROCTYPE) {
          r.set('PROCTYPE','taskTypeProc');
        } else {
          r.set('PROCTYPE',fieldval.PROCTYPE);
        }
        r.set('RUNPARA',r.get('PROC_NAME'));  
      }
      if(objtype=='DATABASE'){
        r.set('CYCLETYPE',r.get('ALIAS'));
      }
      if(objtype=='TEAM'){
        r.set('CYCLETYPE',r.get('TEAM_TYPE'));
      }
      ///检查名称的唯一性
      if(!chekNameIsUniquoe()) {
        alert("名称重复！");
        return false;
      }
    };
    function initNewRecord(){
      for (var key in paramMap) {
        objrecord.set(key.toUpperCase(), paramMap[key]);
      };
      ///通过函数传递的参数
      if(initVals){
          for (var key in initVals) {
              if(typeof  initVals[key]!='object')   
                  objrecord.set(key.toUpperCase(), initVals[key]);
          }
      };
      objrecord.set('CREATER', _UserInfo.usercnname);
      objrecord.set('EFF_DATE', new Date().format("yyyy-mm-dd hh:mm:ss").toLocaleString().toString());
      objrecord.set('STATE', 'NEW');
      objrecord.set('STATE_DATE', new Date().format("yyyy-mm-dd hh:mm:ss").toLocaleString().toString());
      objrecord.set('CURDUTYER', _UserInfo.usercnname);
      objrecord.set('VERSEQ', 1);
      objrecord.set('PATH', 'go.sh');//path
    }
    if(!objStore) objStore = this.getNewMetaObjStore(metaInfo,objid);
    if(actType == 'add'){
      objrecord = objStore.getNewRecord();
      initNewRecord();
      objStore.add(objrecord);
      // objStore.on("beforecommit",function(){
      //   return true;
      // });
    }
    else{
      objrecord = objStore.curRecord;
      var extend_cfg={};
      var extend_cfgstr = objrecord.get('EXTEND_CFG');
      if (extend_cfgstr) {
        extend_cfg = JSON.parse(extend_cfgstr);
        for(var i=0;i<attrArray.length;i++){
          var attr = attrArray[i];
          if(attr.attrname.indexOf("EXTEND_CFG.")>=0){
            var attrKey = attr.attrname.split(".")[1];
            objrecord.set("EXTEND_CFG--"+attrKey,extend_cfg[attrKey]);
          }
        }
      }
    }
    //推荐名称
    var recomObjName = function(fieldName, val,namingType){
      var params = {
    	"db":objStore.curRecord.get("DBNAME"),
        "type":objtype.toLowerCase(),
        "namingType":namingType,
        "force":"y",
        "batch":"n",
        "layer":"",
        "topic":objStore.curRecord.get("TOPICCODE"),
        "words":[""],
        "word":val
      };

      $.ajax({
        type: "POST", 
        async:false,
        url: '/'+contextPath+"/std/names",  
        dataType: 'text',  
        data: JSON.stringify(params),
        contentType: 'application/json;charset=utf-8',
        success: function(data){
          var rs = JSON.parse(data);
          var words = JSON.parse(rs.message);
          if(namingType=="getEnNamed"){
        	  if(words['enword']){
                  var enwords=words['enword'];
                  if(fieldName=='DATACNNAME'){
                	   $("#DATANAME").val(enwords);
                 	   objrecord.set("DATANAME",enwords);
                    }
                    if(fieldName=='PROCCNNAME'){
                    	$("#PROC_NAME").val(enwords);
                 	   objrecord.set("PROC_NAME",enwords);
                    }
                    if(fieldName=='APP_NAME'){
                    	$("#APP_CODE").val(enwords);
                 	   objrecord.set("APP_CODE",enwords);
                    }
                    if(fieldName=='INTER_NAME'){
                    	$("#FULLINTERCODE").val(enwords);
                 	    objrecord.set("FULLINTERCODE",enwords);
                    }
                    if(fieldName=='ZB_NAME'){
                        $("#ZB_CODE").val(enwords);
                 	    objrecord.set("ZB_CODE",enwords);
                    }
                }else{
                	console.log("no word to commands!!");
                	  return;
                  }
          }else if(namingType=="getCnNamed"){
        	  if(words['cnword']){
                  var cnwords=words['cnword'];
                  if(fieldName=='DATANAME'){
                	  $("#DATACNNAME").val(cnwords);
                	   objrecord.set("DATACNNAME",cnwords);
                   }
                   if(fieldName=='PROC_NAME'){
                	   $("#PROCCNNAME").val(cnwords);
                	   objrecord.set("PROCCNNAME",cnwords);
                   }
                   if(fieldName=='APP_CODE'){
                	   $("#APP_NAME").val(cnwords);
                	   objrecord.set("APP_NAME",cnwords);
                   }
                   if(fieldName=='FULLINTERCODE'){
                	   $("#INTER_NAME").val(cnwords);
                	   objrecord.set("INTER_NAME",cnwords);
                   }
                   if(fieldName=='ZB_CODE'){
                	   $("#ZB_NAME").val(cnwords);
                	   objrecord.set("ZB_NAME",cnwords);
                   }
                }else{
                	console.log("no word to commands!!");
              	  return;
                }
          }
        },  
        error: function(res){  
          $("#repJson").val(res);
        }
      });
    };

    var formcfg = ({title:'基本信息', lock:true,   id: 'baseInfoForm',store: objStore,
      fieldChange: function(fieldName, newVal) {
    	  if(objStore.curRecord.get("RECOM_TYPE")=='getEnNamed'&&(fieldName == 'DBNAME' || fieldName == 'TOPICCODE' 
    		  || fieldName=='DATACNNAME'||fieldName=='PROCCNNAME'
    		  ||fieldName=='INTER_NAME'||fieldName=='ZB_NAME'
    	      ||fieldName=='APP_NAME')){
              recomObjName(fieldName, newVal,'getEnNamed');
          }else if(objStore.curRecord.get("RECOM_TYPE")=='getCnNamed'&&(fieldName == 'DBNAME' || fieldName == 'TOPICCODE' 
    		  || fieldName=='DATANAME'||fieldName=='PROC_NAME'
        		  ||fieldName=='FULLINTERCODE'||fieldName=='ZB_CODE'
        	      ||fieldName=='APP_CODE')){
        	  recomObjName(fieldName, newVal,'getCnNamed');
          }
      },
      items: this.getFormItems(attrArray,objStore,'1.基本信息',objtype,actType),
      buttons:objtype.toUpperCase()=='DATABASE'?[{name: '测试',callback: function(){
        var contextPath = window.location['pathname'].split('/')[1];
        var URLP="/"+contextPath+"/crypto/decrypt/des?message="+encodeURIComponent(objStore.curRecord.get('PASSWORD'));
          var password=objStore.curRecord.get('PASSWORD');//ai.remoteData(URLP);
          var driver=objStore.curRecord.get('DRIVERCLASSNAME');
          var url=objStore.curRecord.get('URL');
          var username=objStore.curRecord.get('USERNAME');
          if(!driver||!url||!username){
            alert("信息不完整，无法连接！");
            return false;
          }
        $.ajax({     
              type: 'post',     
              url: '/'+contextPath+'/conntest',     
              data: {
                'driver':driver,
                'url':url,
                'username':username,
                'password':password
               },         
              dataType: "json",     
              success: function(msg) {     
                alert(msg['message']);
              }
          });     
        return false;}}]:null
    });
    ai.showDialogForm(formcfg,beforeOK,afterOK);

    var btn = $(".aui_footer .aui_buttons button:eq(0)");
    if(btn.html() == '测试') {
      btn.addClass('aui_state_highlight');
    }
  },
  editMetaObjBaseInfo:function(options){//{objtype:,objid,objStore,beforeSave,aftSave,
    this.registNewMetaObj($.extend(options,{actType:'edit'}));
  },
  getMetaObjBaseInfo:function(objtype,objid,returnDataType,isDimSwitch){
    returnDataType = returnDataType||'array';
    isDimSwitch = isDimSwitch||true;
    var metaInfo = this.getMetaInfo(objtype);
    var attrArray = this.getMetaAttr(objtype);
    var objStore = new AI.JsonStore({
          sql: "select * from " + metaInfo.tabname + " where XMLID ='" + objid + "' ",
          table: metaInfo.tabname,
          loadDataWhenInit: true,
    });
    if(objStore.getCount() == 0) return null;
    var objrecord = objStore.getAt(0);
    var objInfo = null;
    if(returnDataType=='record'){
      objInfo = objrecord;
    }
    if(returnDataType=='array'){
      objInfo = [];
      for(var i=0;i<attrArray.length;i++){
        var attrval = objrecord.get(attrArray[i].attrname);
        objInfo.push(_.extend(_.pick(attrArray[i],'attrgroup','attrname','attrcnname'),{attrval:attrval}));
      }
    }
    return objInfo;
  },
  showBaseInfo:function(options){///以树的形式显示基本信息
    ///外部参数
    var containerId=options.containerId;
    ///加载基本信息
    var metaModel = this.getMetaModel(this.OBJTYPE);
    var metaInfo = metaModel.metaInfo ;
    this.attrArray = metaInfo.attrArray;
    /****/
    var showExtend = false;
    var curDBInfo = ai.getStoreData("select distinct a.alias dbtype from metadbcfg a where a.dbname = 'METADB'");
    if(curDBInfo.length>0&&curDBInfo[0].DBTYPE=='oracle'){
      var ignoreTopic = ai.getStoreData("select rulecode from metadb_struct a  connect by prior a.rulecode = a.parentcode start with a.rulecode IN ('2015110411390110002','2015110411401010003')");
      // if(_.findIndex(ignoreTopic,{TOPICCODE:objrecord.get('TOPICCODE')})!=-1){
      //   showExtend = true;
      // }
      for(var i=0;i<ignoreTopic.length;i++){
        if(ignoreTopic[i].RULECODE == this.objrecord.get('TOPICCODE')){
          showExtend = true;
          break;
        }
      }
    }
    /****/
    var attrSql = "select OBJTYPE, ATTRGROUP, ATTRNAME, ATTRCNNAME, INPUTTYPE,INPUTPARA, ISNULL, SELVAL, SELMODEL, SEQ, REMARK, DEPENDENCIES, CHECKITEMS from METAOBJCFG"+this._METAPRJ
    +" where objtype='" + this.OBJTYPE + "' "+(showExtend?"":" and ATTRGROUP not like '%扩展%' ")+" order by ATTRGROUP,SEQ ";
    var attrStore =  new AI.JsonStore({
      sql:attrSql,
      pageSize:-1
    });
    
    //元数据表新增进中间表配置
    var tabName = options["tabname"]||metaInfo.tabname;
    var objrecord = options["objrecord"]||metaInfo.objrecord;
    
    this.objStore = new AI.JsonStore({
          sql: "select * from " + tabName + " where  xmlid='" + this.xmlid + "'",
          table: tabName,
          secondTable: "METAOBJ",
          loadDataWhenInit: true,
          key:"XMLID"
    });
    
    this.objrecord = objrecord||this.objStore.getAt(0);
    var catNodes={};
    for(var i=0;i<attrStore.getCount();i++){
      var r=attrStore.getAt(i);
      // if(r.get('ATTRGROUP')&&r.get('ATTRGROUP').indexOf('扩展')!=-1&&!showExtend) continue;
      if(r.get('RULECODE') && r.get('RULECODE').indexOf('CATNODE')>=0) continue;
      var parentcode = catNodes[r.get('ATTRGROUP')];
      if(!parentcode && r.get('ATTRGROUP')) {
        var parentRec=attrStore.getNewRecord();
        parentRec.set('RULECODE',"CATNODE-"+i); 
        parentRec.set('ATTRCNNAME',r.get('ATTRGROUP'));
        attrStore.add(parentRec);
        
        catNodes[r.get('ATTRGROUP')]='CATNODE-'+i;
        parentcode = catNodes[r.get('ATTRGROUP')];
      }

      r.set('RULECODE',"NODE-"+i);  
      r.set('PARENTCODE',parentcode);
      var attrName = r.get('ATTRNAME').toUpperCase();
      if(attrName.indexOf('EXTEND_CFG') != -1){
        var attrarr = attrName.split('.');
        var attrvals = JSON.parse(this.objrecord.get(attrarr[0]));
        if(attrvals&&attrvals[attrarr[1]]){
          r.set('ATTRVAL',attrvals[attrarr[1]]);
        }
        else{
          r.set('ATTRVAL','未知');
        }
      }
      else{
        r.set('ATTRVAL',this.objrecord.get(attrName));
      }
    }

    var config = {
    id : "objbaseInfo",
    //   width : "300",
    renderTo : containerId,
    headerAlign : "left",
    headerHeight : "30",
    dataAlign : "left",
    indentation : "5",
    //folderOpenIcon: "images/folderOpen.gif",
    //folderCloseIcon: "images/folderClose.gif",
    //defaultLeafIcon: "images/defaultLeaf.gif",
    hoverRowBackground : "false",
    folderColumnIndex : "0",
    //itemClick : itemClickEvent,
    columns : [ 

    //{headerText : "规则编号", dataField : "ATTRGROUP", headerAlign : "center", width : "180" }, 
    {headerText : "名称", dataField : "ATTRCNNAME", headerAlign : "left", width : "220", dataAlign : "left" }, 
    //{headerText : "英文名", dataField : "ATTRNAME", headerAlign : "center", width : "120", dataAlign : "center", width : "100"}, 
    {headerText : "值", dataField : "ATTRVAL", headerAlign : "left", width : "320", dataAlign : "left" }

    //, {headerText : "查看", headerAlign : "center", dataAlign : "center", width : "50" }
    ],
    //groupfield:"ATTRGROUP,ATTRCNNAME",//SCHEMA_NAME,TABSPACE,
    keyfield : "RULECODE",
    pkeyfield : "PARENTCODE",
    titlefield : "ATTRCNNAME",
    iconfield : "",
    store:attrStore,
    subtype : 'treegrid'
    };
    var treeGrid = new TreeGrid(config);
    treeGrid.show();
  },
  deleteMetaObj:function(objInfo,actInfo){
    if(!objInfo){
      alert('未选中对象!');
      return;
    }
    
    if(typeof actInfo == 'undefined') actInfo ={};
    var objtype = objInfo.get('OBJTYPE') || actInfo.objtype;
  var delSqls = [];//增加判断数据库是否已授权，增加删除METADB_LIST表中的相应记录2016/5/12
  if(objtype=="TAB"){
        delSqls.push("delete from data_storage_rule where DBNAME = '"+objInfo.get('DBNAME')+"' and DATANAME = '"+objInfo.get('DATANAME')+"' ");
    }
  if(objtype=="DATABASE"){
      var dtdcount = new AI.JsonStore({sql:"select DBNAME from data_trans_database where DBNAME = '"+objInfo.get('DBNAME')+"'"});
      if(dtdcount.getCount()>0){
    	  artDialog.alert("该数据库已赋权给租户，请先在租户管理删除该数据库权限！");
        return false;
      }else{
        delSqls.push("delete from METADB_LIST where DBNAME = '"+objInfo.get('DBNAME')+"'");
        delSqls.push("delete from metadb_struct where DBNAME = '"+objInfo.get('DBNAME')+"'");
        delSqls.push("delete from metaobj_property where XMLID = '"+objInfo.get('DBNAME')+"'");
      }
    }
  	var _self = this;
    var name = artDialog.confirm("确认删除吗?",function(){
    	//var objtype = objInfo.get('OBJTYPE');
        var metaInfo = _self.getMetaInfo(objtype);
        delSqls.push("delete from "+metaInfo.tabname+" where XMLID = '"+objInfo.get('XMLID')+"'");
        delSqls.push("delete from METAOBJ where XMLID = '"+objInfo.get('XMLID')+"'");
        if(objtype=='DATAFLOW'){
          delSqls.push("delete from "+"PROC_SCHEDULE_INFO"+_METAPRJ+" where flowcode='"+objInfo.get('FLOWCODE')+"'");
          delSqls.push("delete from "+"TRANSDATAMAP_DESIGN"+_METAPRJ+" where flowcode='"+objInfo.get('FLOWCODE')+"'");
        }
        var slaveTabs = _self.SLAVE_TABS[objtype];
        if(slaveTabs){
          for(var i=0;i<slaveTabs.length;i++){
            delSqls.push("delete from "+slaveTabs[i]+" where XMLID = '"+objInfo.get('XMLID')+"'");
          }
        }
        var result = ai.executeMultiSql(JSON.stringify(delSqls));
        _self.reload();
        if(result.success){
        	artDialog.tips("删除成功!");
        }
        else{
        	artDialog.tips("删除失败!");
        	return;
        }
       
        _self.fireEvent("deleteMetaObj");
    });
  },
//移交功能的实现
  relegateTo:function(options){
      var _self=this;
      var xmlid = options.objid;
      var objtype = options.objtype;
      var metaModel = this.getMetaModel(objtype);
      var metaInfo = metaModel.metaInfo;
      var metaObjStore = new AI.JsonStore({
        sql:" select * from "+metaInfo.tabname+" where xmlid='"+xmlid+"'",
        key: 'XMLID',
        table:metaInfo.tabname,
        secondTable:'METAOBJ'
      });
      var curRecord = metaObjStore.getAt(0);
      var teamCode = curRecord.get("TEAM_CODE");
      var beforeOK = function(fieldval){  
          curRecord.set("CURDUTYER",fieldval.CURDUTYER);
          metaObjStore.commit();
        }
      var afterOK = function(){
        _self.reload();
        }
      var formcfg = ({title:'移交', lock:true,   id: 'transferTo',
          fieldChange: function(fieldName, newVal) {
          },
          items: [
            // {type:'text',label: '名称:',fieldName:'OBJNAME',value:curRecord.get(metaInfo.keyfield)},
            {type:'combox',label: '负责人:',fieldName:'CURDUTYER',storesql:"select usecnname from metauser a where exists(select 1 from meta_team_role_user where team_code='"+teamCode+"' and username = a.username) ",value:curRecord.get('CURDUTYER')}
          ]
        });
      ai.showDialogForm(formcfg,beforeOK,afterOK,null,80);
  },
  changeMetaObj:function(objtype,objid){
    var store = this.getNewMetaObjStore(this.getMetaInfo(objtype),objid);
    if(store.getCount()>0){
      var r = store.getAt(0);
      r.set('CURDUTYER',_UserInfo.usercnname);
      r.set('STATE','CHANGE');
      r.set('STATE_DATE',new Date().format("yyyy-mm-dd hh:mm:ss").toLocaleString().toString());
      var result = store.commit();
      if(JSON.parse(result).success){
        this.reload();
        r.set('OBJTYPE',objtype);
        this.metaAction({actionkey:'default'},r);
      }
    }
  },
  /*
     actInfo:actionkey 操作名，objid,全局编号，objname:对象名
     action:{actionkey:''},objInfo:{objid,objname,objcnname:,objtype:''}
  */
  metaAction:function(actInfo,objInfo){///如血缘分析，对比分析，查看历史版本，查看变更信息
    var meta = this;
    var objtype=objInfo['objtype']||objInfo['OBJTYPE']||objInfo.get('OBJTYPE')||actInfo.objtype; 
    if(!objtype) objtype=this.config.objtype;
    var metaInfo = this.getMetaInfo(objtype);
    var keyfield = metaInfo.keyfield,namefield = metaInfo.namefield;
    if(keyfield) {
    	var keyfields = keyfield.split(',');
    	metaInfo.multiKeyField = keyfield;
    	metaInfo.keyfield = keyfields[0];//第一位作为主要唯一标识
    	keyfield = keyfields[0];
    }
    var objid = objInfo.get('XMLID'); 
    var objname = objInfo.get('OBJNAME')||objInfo.get(keyfield); 
    var objcnname = objInfo.get('OBJCNNAME')||objInfo.get(namefield); 

    if(!metaInfo) console.error("metaAction:not find metamodel:"+objtype);
    var metaActItems = this.getMetaObjActionItems(objtype);
    var actionkey=actInfo.actionkey||'default';
    var _url="",actfun=null;
    var options = {objtype:objtype,objid:objid,beforeSave:null,aftSave:null,initVals:null}
    if(actionkey=='default'){
      _url=metaInfo.detailurl;
      if(objInfo.get('CURDUTYER')!=_UserInfo.usercnname
        ||(objInfo.get('STATE')!='NEW'&&objInfo.get('STATE')!='CHANGE')){
        _url=metaInfo.runurl;
      }
    }else{
      // var actItem = metaActItems[actionkey];
      var actItem = findItemByActkey(metaActItems, actionkey);
      if(!actItem) {alert('未知的操作：'+actionkey+",请增加操作配置");return;}
      _url=actItem.url;
      actfun = actItem.actfun;
    };

    function findItemByActkey(actionItems, key) {
      var result;
      var keys = _.keys(actionItems);
      for(var i=0; i<keys.length; i++) {
        var myKey = keys[i];
        result = findItemByActkey(actionItems[myKey], key);  //先找所有子项
        if(result) {
          return result;
        }
        if(myKey == key) {
          return actionItems[key];
        }
      }
      return result;
    }

    if(_url){
      _url=_url.replace("{contextPath}",contextPath)
      .replace("{XMLID}",objInfo.get('XMLID')||'')
      .replace("{KEYFIELD}",objInfo.get(keyfield)||'')
      .replace("{NAMEFIELD}",objInfo.get(namefield)||'')
      .replace("{"+keyfield.toUpperCase()+"}",objInfo.get(keyfield)||'')
      .replace("{"+namefield.toUpperCase()+"}",objInfo.get(namefield)||'')
      .replace("{OBJNAME}",objInfo.get('OBJNAME')||objInfo.get(keyfield)||'')
      .replace("{OBJCNNAME}",objInfo.get('OBJCNNAME')||objInfo.get(namefield)||'')
      .replace("{OBJTYPE}",objInfo.get('OBJTYPE')||'')
      .replace("{DBNAME}",objInfo.get('DBNAME')||'')
      .replace("{TEAMCODE}",this.teamcode||paramMap.teamCode||'')
      .replace("{CYCLETYPE}",objInfo.get('CYCLETYPE')||'')
      .replace("{SCHEMA_NAME}",objInfo.get('SCHEMA_NAME')||'')
      //血缘、影响分析
      .replace("{ANNYTYPE}",(objtype=="PROC"?"ETL":"DATA")).replace("{RELANAME}",objInfo.get('OBJNAME')||objInfo.get(keyfield)||'');
      
      if(_url.indexOf("opener=window")>=0){
        window.open(_url);  
      }else if(_url.indexOf("opener=dialog")>=0){
        ai.openDialog(_url,objid+objname,objname||objid,'','');
      }else if(_url.indexOf("opener=service")>=0){
        var result = ai.remoteData(_url); //_url,popTips,callback,method, data
        alert(result.responseMessage);
      }else{
        ai.addTabSheet(objid+objname+actionkey, objcnname||objname||objid,  _url, true );
      }
    }
    else if(actfun){
      eval(actfun);
    }
    else{
      alert("未找到ACTION:"+actionkey+"的触发配置!");
    }
  },
  copyMetaObj:function(objid,objtype){
    localStorage.clipboard = null;
    localStorage.clipboard = JSON.stringify({optype:"copy",objid:objid,objtype:objtype});
  },
  cutMetaObj:function(objid,objtype){
    localStorage.clipboard = null;
    localStorage.clipboard = JSON.stringify({optype:"cut",objid:objid,objtype:objtype});
  },
  pasteMetaObj:function(){
    var SLAVE_TABS = this.SLAVE_TABS;
    if(!localStorage.clipboard || localStorage.clipboard=="null"){
      alert("暂无可粘贴对象");
      return false;
    }
    function changeObjNameCopy(objtype,rec,value){
      if(objtype){
          objtype=objtype.trim();
          if(objtype.toUpperCase()=="TAB"||objtype=="表"){
            rec.set("OBJNAME",value.toUpperCase());
          }else if(objtype.toUpperCase()=="PROC"||objtype=="程序"){
            rec.set("OBJNAME",value.toLowerCase());
          }else{
            rec.set("OBJNAME",value);
          }
        }else{
          rec.set("OBJNAME",value);
        }
    }
    function changeObjNameCut(objtype,rec){
      if(objtype){
          objtype=objtype.trim();
          if(objtype.toUpperCase()=="TAB"||objtype=="表"){
            rec.set("OBJNAME",rec.get("DATANAME").toUpperCase());
          }else if(objtype.toUpperCase()=="PROC"||objtype=="程序"){
            rec.set("OBJNAME",rec.get("PROC_NAME").toLowerCase());
          }
        }
    }
    var clipboard = JSON.parse(localStorage.clipboard);
    var optype = clipboard.optype;
    var xmlid = clipboard.objid;
    var objtype = clipboard.objtype;
    var metaModel = this.getMetaModel(objtype);
    var metaInfo = metaModel.metaInfo;
    var metaObjStore = new AI.JsonStore({
      sql:" select * from "+metaInfo.tabname+" where xmlid='"+xmlid+"'",
      key: 'XMLID',
      table:metaInfo.tabname,
      secondTable:'METAOBJ'
    });
    if(metaObjStore.getCount() < 1){
      alert("原内容已不存在");
      return false;
    }
    var curRecord = metaObjStore.getAt(0);
    if(optype == 'copy'){
      var newXML = ai.guid();
      var _self = this;
      var copyMasterData = function(fieldval){
        var newRecord = $.extend(true,{},  curRecord );
        newRecord.set("XMLID",newXML);
        //newRecord.set("OBJNAME",fieldval.OBJNAME);
        changeObjNameCopy(objtype,newRecord,fieldval.OBJNAME);
        newRecord.set("OBJCNNAME",fieldval.OBJCNNAME);
        newRecord.set("OBJTYPE",objtype);
        newRecord.set(metaInfo.keyfield,fieldval.OBJNAME);
        newRecord.set(metaInfo.namefield,fieldval.OBJCNNAME);
        newRecord.set("TEAM_CODE",_self.teamcode);
        newRecord.set("CREATER",_UserInfo.usercnname);
        newRecord.set("CURDUTYER",_UserInfo.usercnname);
        newRecord.set("STATE","NEW");
        newRecord.set("EFF_DATE",new Date().format("yyyy-mm-dd hh:mm:ss").toLocaleString().toString());
        newRecord.set("STATE_DATE",new Date().format("yyyy-mm-dd hh:mm:ss").toLocaleString().toString());
        for(var i=0;i<_self.config.fieldInfoArray.length;i++){
          curRecord.set(_self.config.fieldInfoArray[i].fieldname.toUpperCase(),_self.config.fieldInfoArray[i].val);
        }
        metaObjStore.add(newRecord);
        var result = JSON.parse(metaObjStore.commit());
        return result.success;
      }
      var copySlaveData = function(fieldval){
        var slaveTabs = SLAVE_TABS[objtype];
        if(slaveTabs){
          for(var i=0;i<slaveTabs.length;i++){
            var slaveTab = slaveTabs[i];
            var slaveObjStore = new AI.JsonStore({
              sql:" select * from "+slaveTab+" where xmlid='"+xmlid+"'",
              pageSize:-1
            });
            var copyObjStore = new AI.JsonStore({
              sql:" select * from "+slaveTab+" where 1=2",
              key: 'XMLID',
              table:slaveTab
            });
            for(var j=0;j<slaveObjStore.getCount();j++){
              var newRecord = $.extend(true,{},  slaveObjStore.getAt(j) ); 
              newRecord.set("XMLID",newXML);
              newRecord.set(metaInfo.keyfield,fieldval.OBJNAME);
              newRecord.set(metaInfo.namefield,fieldval.OBJCNNAME);
              copyObjStore.add(newRecord);
            }
            var result = copyObjStore.commit();
          }
        }
      }
      
      //20160929 chenliang10 获取当前数据库编码
      var metaDbName;
      for(var i=0;i<_self.config.fieldInfoArray.length;i++){
      	if(_self.config.fieldInfoArray[i].fieldname.toUpperCase()=='DBNAME'){
      		metaDbName=_self.config.fieldInfoArray[i].val;
      		break;
      	}
      }
      
      
      var beforeOK = function(fieldval){
    	//20160929 chenliang10 不同数据库下模型名称可以重复
    	var checkSql="select * from "+metaInfo.tabname+" where "+metaInfo.keyfield+"='"+fieldval.OBJNAME+"'";
      	if(objtype=='TAB')
      		checkSql+=" and dbname='"+metaDbName+"'";
        var sameNameObjs = ai.getStoreData(checkSql);
        if(sameNameObjs.length > 0){
          alert("当前名称已存在");
          return false;
        }
        if(copyMasterData(fieldval)){
          copySlaveData(fieldval);
        }
      }
      var afterOK = function(){
        _self.reload();
      }
      
      var title='复制';
      if(objtype=='TAB')
    	  title="模型"+title;
      else if(objtype=='PROC')
    	  title="程序"+title;
      
      
      var formcfg = ({title:title, lock:true,   id: 'diffNameForm',
        fieldChange: function(fieldName, newVal) {
        },
        items: [{type:'text',label: '输入新名称:',fieldName:'OBJNAME',value:curRecord.get(metaInfo.keyfield),notNull:'N',tip:'设置的名称请不要重复!'},
                {type:'text',label: '输入新中文名称:',fieldName:'OBJCNNAME',value:curRecord.get(metaInfo.namefield),notNull:'Y'}]
      });
      ai.showDialogForm(formcfg,beforeOK,afterOK,null,80);
    }
    if(optype == 'cut'){
      curRecord.set("TEAM_CODE",this.teamcode);
      for(var i=0;i<this.config.fieldInfoArray.length;i++){
        curRecord.set(this.config.fieldInfoArray[i].fieldname.toUpperCase(),this.config.fieldInfoArray[i].val);
      }
      changeObjNameCut(objtype,curRecord);
      var result = metaObjStore.commit();
      if(JSON.parse(result).success){
        alert("粘贴成功!");
      }else{
        alert("粘贴失败!");
        return;
      }
      localStorage.clipboard = null;
      this.reload();
    }
  },
  exportObj:function(objtype) {
    // ai.openDialog("/"+ contextPath+"/ftl/me/metaframe/ai.meta.exportchoose?OBJTYPE=" + objtype + "&TEAMCODE=" + this.teamcode,'objChoose','导出对象选择','80%','',null);
    ai.addTabSheet('objChoose', '导出对象选择',  "/"+ contextPath+"/ftl/me/metaframe/ai.meta.exportchoose?OBJTYPE=" + objtype + "&TEAMCODE=" + this.teamcode, true);
  },
  collectObj:function(objtype, objid, collectTo) {
    var url="/"+contextPath+"/ftl/catalog/dataindex/collectObj?XMLID="+objid+"&OBJTYPE="+objtype+"&collectTo="+collectTo;
    ai.openDialog(url,objid,"选择收藏目录",'','');
  }

});
   /** 
 * @class
 * @extends Event.Class
 */
AI.MetaList=AI.Meta.$extend({
  _listeners:{},
  defaultOptions:{
    containerId:'',
    title:'对象列表',
    page:'tpllist.html',
    sql:"SELECT XMLID,OBJNAME,OBJCNNAME,OBJTYPE,DBNAME,TOPICCODE,CYCLETYPE,TEAM_CODE,CREATER,EFF_DATE,CURDUTYER,STATE,STATE_DATE,VERSEQ,REMARK FROM METAOBJ ",
    columns:[
      {header: "类型", dataIndex: "OBJTYPE", headerAlign: "center",width: "80",sortable:true,dimStore:new AI.JsonStore({sql:"SELECT objtype,objname FROM metaobjmodel group by objtype,objname",pageSize:-1})
      ,render:function(rowData,colVal){
        if(colVal=='folder') return '目录';
        if(this.dimStore&&this.dimStore.getCount()>0){
          var dim = _.find(this.dimStore.root,function(obj){
            if(obj.OBJTYPE == colVal) return obj;
          });
          colVal = dim&&dim.OBJNAME?dim.OBJNAME:colVal;
        }
        return colVal;
      }},
      {header: "名称", dataIndex: "OBJNAME", headerAlign: "center",width: "180",sortable:true,maxLength:30},
      {header: "中文名", dataIndex: "OBJCNNAME", headerAlign: "center", dataAlign: "center", width: "250",sortable:true,maxLength:30 },
      {header: "备注",dataIndex:'REMARK', headerAlign: "center", dataAlign: "center", width: "250" ,sortable:true,maxLength:50}
    ],
    bodyWithDetail:'<div class="repeater-canvas col-md-9" style="padding-left:1px;padding-right:1px;"></div>  <div class="repeater-detail col-md-3" style="padding-left:1px;"></div>',
    bodyHtml:'<div class="repeater-canvas">  </div> ',
    viewtype:'card,list',
    card:{
    //width:260,height:50,
    tpl:'<div class="dacptiles select" rowindex="{{ROWINDEX}}" id="{{XMLID}}"  objtype="{{OBJTYPE}}" name="{{OBJNAME}}" title="{{OBJCNNAME}}"  style="width: 80px;height: 80px; overflow:hidden">'
      + '<span class="icon glyphicon {{OBJICON}}" aria-hidden="true"></span>'
      +'<span class="title">{{OBJNAME}}</span>'
      +'</div>'
    },
    toolbarconfig:[
      //{type:'search',fieldLabel:'名称',width:120,name:'name',where:"(OBJNAME like '%{name}%' or OBJCNNAME like '%{name}%')"}
    ],
    loadtype:'paas'
  },///显示界面最基本信息 
  control:null,
  __init__ : function(options) {
    this.$super(options);
    this._listeners={};
    if(options.show)  this.showList(options);
    },
  destroy:function(){
    $('#'+this.options.containerId).empty();
    this.$super();
  },
  beforeShow:null,///显示之前,提供给外部的注册函数
  getToolBarConfig:function(config,actions){///config-外部传入的toolbar,actions-外部传入的actionList
    var items = this.getMetaObjActionItems(this.objtype,'toolbar');
    if(config&&config.length>0){//优先外部传入
      if(!actions||_.keys(actions).length==0||!items) return config;
      var itemGroup = {type:'buttongroup',dropIndex:'0',fieldLabel:'更多操作...',name:'create',fields:[]};
      for (key in actions){
        if(actions[key].dealtype == 'add'){
          var item = items[key];
          itemGroup.fields.push({actionId:key,name:key,fieldLabel:item.name});
        }
      }
      if(itemGroup.fields.length>0){
        config.push(itemGroup);
      }
      return config;
    }
    //if(this.objtype == 'folder') return this.defaultOptions.toolbarconfig;
    var self = this;
    if(this.objtype == 'folder'){
    	return [{type:'search',fieldLabel:'名称',width:120,name:'name',where:"(OBJNAME like '%{name}%' or OBJCNNAME like '%{name}%')",fn:function(){
    		var where = " where 1=1 ";
    		for(var i=0;i<self.gridUx.toolbars.length;i++){
			    var itemUx = self.gridUx.toolbars[i];
			    if(itemUx&&itemUx.getValue()&&itemUx.config.where){
				where += " and "+itemUx.config.where.replace(eval('/{'+itemUx.config.name+'}/g'),itemUx.getValue());
			    }
			}
    		var sql = "select * from metaobj "+where+(self.teamcode?" and team_code = '"+self.teamcode+"'":"");
    		var curNode = self.config.treeNode;
    		if(curNode.objtype=='DATABASE'){
    			sql += " and dbname = '"+curNode.id+"'";
    		}
    		if(curNode.objtype=='TOPIC'){
    			sql += " and topiccode like '"+curNode.id+"%'";
    		}
    		self.config.store = self.gridUx.store = new AI.JsonStore({
    			sql:sql,
    			key:'XMLID'
    		});
      	  	self.reload();
        },cfn:function(){
        	self.config.store = self.gridUx.store = new AI.JsonStore({
                data:[],
                key:"XMLID"
            });
          	var childNodes = self.config.treeNode.children||[];
            for(var i=0;i<childNodes.length;i++){
              var node =childNodes[i];
              var itemRec=self.gridUx.store.getNewRecord();
              itemRec.set('OBJTYPE','folder');
              itemRec.set('NODETYPE','');
              itemRec.set('OBJICON','glyphicon-folder-open');
              itemRec.set('XMLID',node.id);
              itemRec.set('OBJCODE',node.id);
              itemRec.set('OBJNAME',node.id);
              itemRec.set('OBJCNNAME',node.name);
              self.gridUx.store.add(itemRec);
            }
            self.reload();
            }
        }]
    }
    var toolbarconfig = [];
    var metaInfo = this.getMetaInfo(this.objtype);
    if(metaInfo.parentcode=='META-OTHER'){
      toolbarconfig = [
        {type:'text',fieldLabel:'对象名称',width:120,name:'name',where:"(upper(OBJNAME) like upper('%{name}%') or upper(OBJCNNAME) like upper('%{name}%'))"},
        {type:'button',fieldLabel:'查询',width:120,name:'query',actionId:'queryMetaObj'},
        {type:'buttongroup',dropIndex:'1',fieldLabel:'新建...',name:'create',fields:[{actionId:'create'+metaInfo.objtype,name:'create'+metaInfo.objtype,fieldLabel:'新建'+metaInfo.objname}]}      
      ]
      var collect= {type:'button',fieldLabel:'采集',width:120,name:'query',fn:function(){
        
        var html = '<div id="progressbar"></div>';
        ymPrompt.succeedInfo({message:html,width:200,height:150,btn:null,showMask:true,closeBtn:true,title:'采集中...'});
        
        var progressbar = $( "#progressbar" );
          progressbar.html('<div class="progress-label"></div>');
              progressLabel = $( ".progress-label" );
              progressbar.progressbar({
                value: false,
                change: function() {},
                complete: function() {
                 // progressLabel.text( "Complete!" );
                }
              });
        var objid = $("tr[class='datarow active']").attr('id');
        var objStore = new AI.JsonStore({sql:" select * from "+metaInfo.tabname+" where xmlid='"+objid+"'"});
        $.ajax({     
              type: 'get',     
              url: '/'+contextPath+'//collectservice/'+objStore.getAt(0)&&objStore.getAt(0).get("DBNAME"),     
              data:null,         
              dataType: "json", 
              success: function(msg) {
                
                if(200==msg['code']){
                
                  $.ajax({     
                          type: 'get',     
                          url: '/'+contextPath+'/meta/cmp/start/'+objStore.getAt(0)&&objStore.getAt(0).get("DBNAME")+'/'+msg['result'],   
                          data:null,         
                          dataType: "json",     
                          success: function(msg) {  
                            if(200==msg['code']){                               
                              alert(msg['message']);
                            }else{
                              alert("采集失败:"+msg['message']);
                            }
                            $(".ymPrompt_close").click();
                            
                          }
                      });
                }else{
                  alert("采集失败:"+msg['message']);
                  $(".ymPrompt_close").click();
                }
                
              }
          });
        $( "#progressbar" ).empty();
      }};
      if(metaInfo.objname=='数据库'){
        toolbarconfig.push(collect);
      }
    }
    else{
       toolbarconfig = [
         {type:'text',fieldLabel:'对象名称',width:120,name:'name',where:"(upper(OBJNAME) like upper('%{name}%') or upper(OBJCNNAME) like upper('%{name}%'))"},
         {type:'combox',fieldLabel:'状态',width:210,name:'state',storesql:"select rowcode,rowname from metaedimdef where dimcode = 'DIM_STATE'",where:"state = '{state}'"},
         {type:'button',fieldLabel:'查询',width:120,name:'query',actionId:'queryMetaObj'}
 //        {type:'buttongroup',dropIndex:'1',fieldLabel:'新建...',name:'create',fields:[{actionId:'create'+metaInfo.objtype,name:'create'+metaInfo.objtype,fieldLabel:'新建'+metaInfo.objname}]}
       ];
//       var itemGroup = {type:'buttongroup',dropIndex:'0',fieldLabel:'操作...',name:'create',fields:[]};
//       for (key in items) {
//         if(!actions||!actions[key]||actions[key] != 'delete'){
//           itemGroup.fields.push({actionId:key,name:key,fieldLabel:items[key].name});
//         }
//       }
//       if(itemGroup.fields.length>0){
//         toolbarconfig.push(itemGroup);
//       }
    }
    if(toolbarconfig.length==0) return this.defaultOptions.toolbarconfig;//默认配置优先级最低
    return toolbarconfig;
  },
  getViewColumnConfig:function(colConfig){
    //优先外部传入，元模型中展示配置次之，最后默认
    if(colConfig) return colConfig;

    var columnStr = this.getMetaProPerty(this.objtype,'viewlist_column');
    
    if(columnStr){
      var viewColumn = null; 
      try{
        viewColumn = eval(columnStr);
      }catch(e){
        console.log('请检查元模型配置;'+e);
      }finally{
        return viewColumn;
      }
    }
  },
  buildContextMenu:function(selector){
    var self=this;
    var runAction = function(key, opts){
      $('.context-menu-list').filter(':visible').trigger('contextmenu:hide');
      // var objStore = self.config.store;     
      var objid = $(this).attr('id');
      var objtype = $(this).attr('objtype');
      if(".repeater-thumbnail-cont,.repeater-list-wrapper"==opts.selector&&key=='paste'){
        var clipboard = JSON.parse(localStorage.clipboard);
        objtype = clipboard.objtype;
        objid = clipboard.objid;
      }
      var metaModel = self.getMetaModel(objtype);
      var metaInfo = metaModel.metaInfo;
      var objStore = new AI.JsonStore({sql:" select * from "+metaInfo.tabname+" where xmlid='"+objid+"'"});
      if(objStore.getCount()==0) return;
      var objInfo = objStore.getAt(0);
      if(objInfo!=null&&!objInfo.get('OBJTYPE')){
        objInfo.set('OBJTYPE',objtype);
      }
      self.metaAction({actionkey:key},objInfo);
    }
    $.contextMenu({
      //selector: selector||'.dacptiles,tr.datarow', 
      selector: selector||'.repeater-thumbnail-cont,.repeater-list-wrapper',
      build: function($trigger, e) {
        // alert(1);
        // $('.context-menu-list').filter(':visible').trigger('contextmenu:hide');
        // this callback is executed every time the menu is to be shown
        // its results are destroyed every time the menu is hidden
        // e is the original contextmenu event, containing e.pageX and e.pageY (amongst other data)
        var objtype = ($trigger.attr("objtype"));
        var objid = $trigger.attr("id");
        // $trigger.trigger('click');
        // console.log(self.config.store.curRecord);
        // var curRec=self.config.store.curRecord;
        /*if(typeof(objtype) == "undefined"||typeof(objid) == "undefined"){
          objtype='';
          objid='';         
        }*/
        var items = self.getContextMenu(objtype,objid);
        
        return {
          callback: runAction,
          // items:self.getMetaContextMenu(objtype,curRec),
          // items:items[objtype],
          items:self.getContextMenu(objtype,objid),
          items1: {
            "edit": {name: "Edit", icon: "edit"},
            "cut": {name: "Cut", icon: "cut"},
            "copy": {name: "Copy", icon: "copy"},
            "paste": {name: "Paste", icon: "paste"},
            "delete": {name: "Delete", icon: "delete"},
            "fold1": {
              "name": "Sub group", 
              "items": {
                "fold1-key1": {"name": "Foo bar"},
                "fold2": {
                    "name": "Sub group 2", 
                    "items": {
                        "fold2-key1": {"name": "alpha"},
                        "fold2-key2": {"name": "bravo"},
                        "fold2-key3": {"name": "charlie"}
                    }
                },
                "fold1-key3": {"name": "delta"}
              }
            },
            "sep1": "---------",
            "quit": {name: "Quit", icon: function($element, key, item){ return 'context-menu-icon context-menu-icon-quit'; }}
          }
        }
      }
    });
    $("html").bind("click", function() {
      $('.context-menu-list').filter(':visible').trigger('contextmenu:hide');
    }); 
  },
  getViewConfig:function(config){
    var objtype=config.objtype;
    var metaModel=this.getMetaModel(objtype);
    var metaInfo={}
    if(metaModel && metaModel.metaInfo) metaInfo = metaModel.metaInfo;
    config.title= config.title||metaInfo.objname;

    var itemStore=config.store;
    var viewsql = config.sql||this.getMetaProPerty(this.objtype,'viewlist_sql')||this.defaultOptions.sql;

    ///设置store
    if(!itemStore){
      itemStore = new AI.JsonStore({
        sql: viewsql+" where 1=1 "+(config.filter||''),
        pageSize:50,
        key:"XMLID"
      });
    }
    config.store= itemStore;
    
    var self=this;
    var preParaDataStore=function(store){
      for(var i=0;i<itemStore.getCount();i++){
        var r=itemStore.getAt(i);
        if(!r.get('OBJNAME')) r.set('OBJNAME',r.get(metaInfo.keyfield));
        if(!r.get('OBJCNNAME')) r.set('OBJCNNAME',r.get(metaInfo.namefield));
        if(!r.get('OBJTYPE')) r.set('OBJTYPE',objtype);
        r.set('ROWINDEX',i);
        if(!r.get('OBJICON')) r.set('OBJICON',self.getMetaObjIcon(r.get('OBJTYPE')||objtype));
        if(r.get("TEAM_TYPE")=='1')r.set("TEAM_TYPE","每表申请免授权");
        if(r.get("TEAM_TYPE")=='2')r.set("TEAM_TYPE","规则授权");
        if(r.get("TEAM_TYPE")=='3')r.set("TEAM_TYPE","免授权");
      }
    };
    config.preParaDataStore=config.preParaDataStore||preParaDataStore;
    
    if(!config.card||!config.card.tpl){//外部未传入则从数据库配置中获取
      var card = null;
      var cardTpl=this.getMetaProPerty(objtype,'viewcarttpl');
      if(cardTpl) cardTpl = cardTpl.replace('{contextPath}',contextPath);
     
      if(cardTpl && cardTpl.length>20) {///
           card = {tpl:cardTpl};
       }
      if(objtype == 'folder'){
        card={tpl:'<div class="dacptiles select" rowindex="{{ROWINDEX}}" id="{{XMLID}}"  objtype="{{OBJTYPE}}" name="{{OBJNAME}}" title="{{OBJCNNAME}}"  style="width: 80px;height: 80px; overflow:hidden">'
            + '<span class="icon glyphicon {{OBJICON}}" aria-hidden="true"></span>'
            +'<span class="title">{{OBJCNNAME}}</span>'
            +'</div>'};
      }
      if(card) config.card = card;
    }
    config.bodyHtml='<div class="repeater-canvas col-md-12" style="padding-left:1px;padding-right:1px;"></div> ';
  },
  showListFromMetaObj:function(config){////统一从元模型加载
    var self=this;
    config.toolbarconfig = this.getToolBarConfig(config.toolbarconfig||null,config.actions||null);
    config.columns = this.getViewColumnConfig(config.columns||null);
    this.getViewConfig(config);
    var config = $.extend(false,{},  this.defaultOptions,config ); //TODO
    var objtype=config.objtype;
    this.config=config;
    this.config.onReady=function(){
       if(self.config.onLoaded) self.config.onLoaded();
       self.buildContextMenu();
       self.fireEvent("loaded");
    };
    config.rowRender = function($row,rowData){
      $row.attr('id', rowData.XMLID).attr('objtype',rowData.OBJTYPE); 
    }
    var metaInfo = this.getMetaInfo(this.objtype);//TODO
    var newConfig = $.extend(true,{},config);
//    if(this.objtype=='folder'||metaInfo.parentcode=='META-OTHER'){
//      newConfig.columns.splice(0,1);
//      newConfig.columns.splice(3,1);
//    }

    this.gridUx=  new  AI.GridUx(newConfig);
    this.buildListEvent();
  },
  showListFromBaseTab:function(config){///没有纳入到metaobj统一管理的加载方式
    var self=this;
    config.toolbarconfig = this.getToolBarConfig(config.toolbarconfig||null,config.actions||null);
    this.getViewConfig(config,'metatable');
    var config = $.extend(true,{},  this.defaultOptions,config ); ///扩展对象属性
    var objtype=config.objtype;
    var metaModel=this.getMetaModel(objtype);
    var metaInfo = metaModel.metaInfo;
    this.config=config; 
    this.gridUx=new AI.GridUx($.extend(config,{sortItems:metaModel.attrArray},
        {rowRender:function ($row,rowData) {
          $row.attr('id', rowData[metaInfo.keyfield]).attr('objtype',objtype);
        }
    }));
    this.buildListEvent();
  },
  buildListEvent:function (){
    var self=this;
    var _bindRightMenuEvent = function(){
      // self.gridUx.control.find('.dacptiles,tr.datarow').each(function(i,e){
      //   self.buildContextMenu($(this).attr('id')?'#'+$(this).attr('id'):'',$(this).attr('objtype'));
      // });
      self.buildContextMenu('.dacptiles,tr.datarow');
    }
    _bindRightMenuEvent();

    this.gridUx.on("dblclick",function(e){
      self.dblClick($(e.currentTarget).attr('id'),$(e.currentTarget).attr('objtype'));
    });

    this.gridUx.on('click',function(e){
      self.click(e);
    });
    
    //UX工具栏单击事件
    this.gridUx.on("toolbarclick",function(actionId){
      self.toolbarClick(actionId);
    });
    this.gridUx.on("loaded",function(){
      _bindRightMenuEvent();
      self.fireEvent("loaded");
    });
  },
  showList:function(config){
    this.objtype = config.objtype;
    this.teamcode = config.teamcode;
    $('#'+config.containerId+'_myRepeater').repeater('destroy');
    if(this.gridUx&&this.gridUx.control)  delete this.gridUx.control;
    $('#'+ config.containerId).empty();
    this.showListFromMetaObj(config);
  },
  showDetailInfo:function(){
    var r=this.config.store.curRecord;
    if(!r) return;
     
    var html='<table class="table"><h5>详细信息</h5>';
    html+='<thead> <tr >  <th width="20px">#</th> <th>值</th> </tr> </thead>';
    html+='<tbody>';
    for(var key in r.data){
      if(r.data[key]){
      html+='<tr><td width="20px">'+key+'</td><td>'+r.data[key]+'</td></tr>';
      }
    };
    html+='</tbody><table>';
    $(".repeater-detail").empty().html(html); 
  },
  getContextMenu:function(objtype,objid){
   $('.context-menu-list').filter(':visible').trigger('contextmenu:hide');
   var items=null; 
   var objInfo=null;
   if(typeof(objtype) == "undefined"||typeof(objid) == "undefined"){
    items = this.getMetaObjActionItems('*','rightmenu_global');
   }else{
     objtype = objtype||this.objtype; 
     if(objtype == 'folder') return;
     objInfo = this.getMetaObjBaseInfo(objtype,objid,'record');
     items = this.getMetaObjActionItems(objtype,'rightmenu');
   }
         
    var contextMenu = this.config.contextMenu;//外部传入的菜单
    var menuItems = this.config.menuItems;//数据库配置基础上额外配置项
    

    if(contextMenu&&_.keys(contextMenu).length > 0){//优先外部传入
      if(!menuItems||_.keys(menuItems).length==0||!items) return contextMenu;
      for (key in menuItems){
        if(menuItems[key].dealtype == 'add'){
          items[key].icon = " " + items[key].icon;
          contextMenu[key] = items[key];
        }
      }
      return contextMenu;
    }
    //外部未传入,以数据库配置为主
    var resultItems = {};
    var addItems = _.omit(menuItems,_.keys(items));//外部在数据库配置基础上新增的
    for (key in items) {
      items[key].icon = " " + items[key].icon;
      if(items[key].getright){//权限
        items[key].disabled = false;//TODO
        var result = items[key].getright(objInfo,_UserInfo,this.getMetaInfo(objtype),this.config.loadtype);
        if(result == 'hide') continue;
        if(result == 'disabled'){
          items[key].disabled = true;
          // items[key].display = 'none';
        }
      }
      if(menuItems&&menuItems[key]&&menuItems[key].dealtype == 'reload'){
        resultItems[key] = menuItems[key];//外部覆盖部分数据库配置的
      }
      else if(menuItems&&menuItems[key]&&menuItems[key].dealtype == 'delete'){

      }
      else{
        resultItems[key] = items[key];
      }
    }
    return _.extend(resultItems,addItems);
  },
  dblClick:function(objid,objtype){
    var result = true;
    var objtype = objtype||this.objtype;
    if(this.config.dblClick){
      result = this.config.dblClick(objid,objtype);
    }
    if(result){
      var rec=this.config.store.getRecordByKey(objid);
      if(!rec.get('OBJTYPE')) rec.set('OBJTYPE',objtype)
      this.config.store.curRecord=rec;
      this.fireEvent("dblclick",objid);
      if(rec.get("OBJTYPE")=="folder") return;
      if(!rec) return;
      var actionInfo={actionkey:''};
      this.metaAction({actionkey:'default'},rec);
    }
  },
  click:function(e){
    var result = true;
    if(this.config.click){
      result = this.config.click(e);
    }
  },
  toolbarClick:function(actionId){
    var self = this;
    var result = true;
    if(this.config.toolbarClick){
      result = this.config.toolbarClick(actionId);
    }
    if(result){
      if(actionId.indexOf("create") != -1){
        var objType = actionId.replace('create','').toUpperCase();
        var initVals = {};//
        if(self.config.fieldInfoArray){
        for(var i=0;i<self.config.fieldInfoArray.length;i++){
          var fieldInfo = self.config.fieldInfoArray[i];
          if(!initVals[fieldInfo.fieldname]) initVals[fieldInfo.fieldname] = fieldInfo.val;
        }
        }
        var beforeSave = function(fieldval,objStore){
        }
        var aftSave = function(a){

        };
        
        if(!objType) objType=this.objtype;
        
        self.registNewMetaObj({objtype:objType,teamcode:self.teamcode,initVals:initVals,aftSave:aftSave,beforeSave:beforeSave});
      }
      else if(actionId.indexOf("export") != -1){
    	  var objType = actionId.replace('export','').toUpperCase();
    	  self.exportObj(objType);
      }
      else{
        self.metaAction({actionkey:actionId||'default'},objInfo||'');
      }
    }
  },
  reload:function(sql){
    this.gridUx.reload(sql);
  }
});
 
